package io.renren.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.entity.CodeGenConfig;
import io.renren.entity.DbConfig;
import io.renren.service.SysGeneratorService;
import io.renren.utils.PageUtils;
import io.renren.utils.Query;
import io.renren.utils.R;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/generator")
public class GeneratorConfigController {

    @Autowired
    private SysGeneratorService sysGeneratorService;

    private ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/queryTable")
    public R queryTable(@RequestBody Map<String, Object> params) {
        try {
            DbConfig dbConfig = objectMapper.convertValue(params.get("dbConfig"), DbConfig.class);
            String tableName = (String) params.get("tableName");
            List<Map<String, Object>> tableInfo = sysGeneratorService.queryTableInfo(dbConfig, tableName);
            return R.ok().put("tableInfo", tableInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败：" + e.getMessage());
        }
    }

    @PostMapping("/generateCode")
    public void generateCode(@RequestBody Map<String, Object> params, HttpServletResponse response) throws IOException {
        try {
            DbConfig dbConfig = objectMapper.convertValue(params.get("dbConfig"), DbConfig.class);
            CodeGenConfig codeConfig = objectMapper.convertValue(params.get("codeConfig"), CodeGenConfig.class);
            List<String> tables = (List<String>) params.get("tables");

            byte[] data = sysGeneratorService.generatorCode(dbConfig, codeConfig, tables.toArray(new String[0]));

            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"renren.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(500, "生成失败：" + e.getMessage());
        }
    }


    @PostMapping("/testDb")
    public R testConnection(@RequestBody DbConfig dbConfig) {
        try {
            Class.forName(dbConfig.getDriver());
            try (Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://" + dbConfig.getHost() + "?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai",
                    dbConfig.getUsername(),
                    dbConfig.getPassword()
            )) {
                if (conn != null && !conn.isClosed()) {
                    return R.ok("连接成功！");
                }
            }
            return R.error("连接失败！");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("连接异常: " + e.getMessage());
        }
    }

}
